#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define NUM 3

class Ticket
{
private:
    int tickets;
    pthread_mutex_t mtx;
public:	
    Ticket() : tickets(1000)
    {
	pthread_mutex_init(&mtx, NULL);
    }
    ~Ticket()
    {
	pthread_mutex_destroy(&mtx);
    }

    bool GetTicket()
    {	
	pthread_mutex_lock(&mtx);	
	bool res = true;
	if(tickets > 0)
	{
	    usleep(1000);
	    cout << "我是[" << pthread_self() << "], 我抢到的票是 " << tickets << endl;
	    tickets--;
	}
	else
	{
	    res = false;
	}
	pthread_mutex_unlock(&mtx);
	return res;
    }	
};

Ticket t;
void* thread_run(void* args)
{
    int num = *(int*)args;
    delete (int*)args;
    while(1)
    {
        if(!t.GetTicket())
 	{
	    cout << "票已经被抢完了" << endl;
	    break;
	}
    }
}	

int main()
{
    pthread_t tid[3];
    for(int i = 0;i < NUM;++i)
    {
	int * num = new int(i);
	pthread_create(tid+i, NULL, thread_run, (void*)num);
    }
    for(int i = 0;i < NUM;++i)
    {
	pthread_join(tid[i], NULL);
    }

    return 0;
}
